package cn.itsource.template;

import cn.itsource.properties.CosProperties;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.util.UUID;

@Slf4j
public class CosTemplate {

    private final CosProperties properties;

    public CosTemplate(CosProperties properties){
        this.properties = properties;
    }


    //inputStream ：文件流,folder ：文件存储目录,extName ：扩展名
    public String uploadForStream(InputStream inputStream,String folder ,String extName){
        COSClient cosClient = createCosClient();

        // 指定文件将要存放的存储桶
        String bucketName = properties.getBucketName();

        // 指定文件上传到 COS 上的路径，
        String fileName = UUID.randomUUID().toString();

        String key = folder+"/"+fileName+"."+extName;
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream,new ObjectMetadata());
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        System.out.println(putObjectResult);

        //https://%s.cos.%s.myqcloud.com/%s
        String fileUrl = String.format(properties.getFileUrl(), bucketName,properties.getRegion(),key);
        log.info("上传成功，文件地址：{}",fileUrl);
        return fileUrl;
    }

    //创建COS客户端
    private COSClient createCosClient(){
        // 1 初始化用户身份信息（secretId, secretKey）。
        String secretId = properties.getSecretId();//用户的 SecretId，
        String secretKey = properties.getSecretKey();//用户的 SecretKey，
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);

        // 2 设置 bucket 的地域, COS 地域的简称请参见 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region(properties.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);

        // 这里建议设置使用 https 协议
        // 从 5.6.54 版本开始，默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);

        // 3 生成 cos 客户端。
        return new COSClient(cred, clientConfig);
    }
}
